//
//  MYKSCrashManager.m
//  MySDK
//
//  Created by shuai on 2025/11/1.
//

#import "MYKSCrashManager.h"
#import "KSCrashReport.h"
#import "KSCrashReportFilter.h"
#import "KSCrash.h"
#import "KSCrashConfiguration.h"
#import "KSCrashInstallationConsole.h"
#import "MYKSCrashFilter.h"

@interface MYKSCrashManager()

@end

@implementation MYKSCrashManager

+ (instancetype)sharedManager {
    static MYKSCrashManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

// 回调函数实现，需匹配 KSCrashDidWriteReportCallback 的签名
void crashDidWriteReportCallback(const KSCrash_ExceptionHandlingPlan * _Nonnull const plan,
                                int64_t reportID) {
    NSLog(@"已写入崩溃报告，报告ID：%lld", reportID);
}

- (void)initKSCrash {
    // 创建KSCrash配置
    KSCrashConfiguration *config = [[KSCrashConfiguration alloc] init];

    config.didWriteReportCallback = crashDidWriteReportCallback;
    // 监控信号和NSException异常
    config.monitors = KSCrashMonitorTypeSignal | KSCrashMonitorTypeNSException;
    NSError *error = nil;

    // 初始化控制台输出的 Installation
    KSCrashInstallationConsole *consoleInstallation = [[KSCrashInstallationConsole alloc] init];
    consoleInstallation.printAppleFormat = NO;

    // 添加自定义过滤器（基于地址范围筛选 SDK 相关的崩溃报告）
    // 可以传入自定义的 SDK 标识符，默认使用 "MySDK"
    MYKSCrashFilter *sdkFilter = [[MYKSCrashFilter alloc] initWithSDKIdentifier:@"MySDK"];
    [consoleInstallation addPreFilter:sdkFilter]; // 作为前置过滤器生效

    
    // 安装配置
    BOOL success = [consoleInstallation installWithConfiguration:config error:&error];
    if (!success) {
        NSLog(@"KSCrash 安装失败：%@", error.localizedDescription);
    } else {
        NSLog(@"KSCrash 安装成功，已配置地址范围筛选");
    }

    // 立即发送所有已存储的报告（如果有）
    [consoleInstallation sendAllReportsWithCompletion:^(NSArray<id<KSCrashReport>> * _Nullable filteredReports, NSError * _Nullable error) {
        if (error) {
            NSLog(@"发送失败：%@", error.localizedDescription);
            return;
        }
        if (filteredReports.count > 0) {
            NSLog(@"筛选后有 %ld 条 SDK 相关崩溃报告：", filteredReports.count);
            for (id<KSCrashReport> report in filteredReports) {
//                NSLog(@"报告内容：%@", report.untypedValue);
            }
        } else {
            NSLog(@"没有 SDK 相关的崩溃报告");
        }
    }];
}

@end
